# -*- coding: utf-8 -*-

import sys
import urllib
import urllib2

def get_user_token(projectname, username, password):
    """获取token。
    
    根据用户和密码，到keystone处获取token。

    参数：
        username: 用户名。 
        password: 密码。

    返回值：
        返回获取的token，字符串格式。
    """
    url = 'http://controller:35357/v3/auth/tokens'
    body = ('{"auth": {"scope": {"project": {"domain": {"name": "Default"}, "name": "%s"}},' 
        '"identity": {"password": {"user": {"domain": {"name": "Default"}, "password": "%s", "name": "%s"}},' 
        '"methods": ["password"]}}}'%(projectname, password, username))
    headers = {'Content-Type': 'application/json'}
    req = urllib2.Request(url, body, headers)
    response = urllib2.urlopen(req)
    return response.info()['X-Subject-Token'] 

def manual_migration(virtual_id, server_name, projectname="admin", username="admin", password="bjtungirc"):
    """手动热迁移。

    将指定的虚拟机迁移到指定的物理机。

    参数：
        virtual_id：要迁移的虚拟机ID。
        server_name：虚拟机迁移的目的物理机名称。

    返回值：
        无
    """
    url = 'http://controller:8774/v2.1/servers/%s/action'%(virtual_id)
    body = '{"os-migrateLive": {"disk_over_commit": false, "block_migration": true, "host": "%s"}}'%(server_name)
    token = get_user_token(projectname, username, password)
    print token
    print url
    print body
    headers = {"Accept": "application/json", "User-Agent": "python-novaclient"}
    #headers.update({"OpenStack-API-Version": "compute 2.53", "X-OpenStack-Nova-API-Version": 2.53})
    headers.update({"X-Auth-Token": token, "Content-Type": "application/json"})
    req = urllib2.Request(url, body, headers)
    response = urllib2.urlopen(req)
    return True

def main():
    if len(sys.argv) == 3:
        return manual_migration(sys.argv[1], sys.argv[2])
    elif len(sys.argv) == 6:
        return manual_migration(sys.argv[1], sys.argv[2], sys.argv[3]. sys.argv[4], sys.argv[5])
    else:
       return False

if __name__ == "__main__":
    main()

